import { useState, useEffect } from 'react';
import { getDictionaryByTypeApi } from '../api/dictionaryApi';

// 字典Hook - 用于获取特定类型的字典数据
export const useDictionary = (dictType, onlyActive = true) => {
  const [dictList, setDictList] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchDict = async () => {
    if (!dictType) return;
    
    setLoading(true);
    try {
      const params = { dictType };
      if (onlyActive) {
        params.status = '0'; // 只获取启用状态的数据
      }
      const response = await getDictionaryByTypeApi(params);
      if (response.code === '0' || response.code === 200) {
        const list = response.data || [];
        setDictList(list.map(item => ({
          value: item.dictValue,
          label: item.dictLabel
        })));
      }
    } catch (error) {
      console.error('获取字典数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDict();
  }, [dictType]);

  return { dictList, loading, refetch: fetchDict };
};

// 字典工具函数
export const dictUtils = {
  // 根据字典类型和值获取标签
  getLabel: (dictList, value) => {
    const item = dictList.find(item => item.value === value);
    return item ? item.label : value;
  },

  // 根据字典类型和标签获取值
  getValue: (dictList, label) => {
    const item = dictList.find(item => item.label === label);
    return item ? item.value : label;
  }
};
